Observed log-chlorophyll at representative station in SF Bay Delta region.

library(tidyverse)
library(lubridate)
library(mgcv)  
library(plotly)
library(WRTDStidal)
library(gridExtra)
source('R/funcs.R')

# flow data, left moving window average of 30 days
data(sf_fldat)
fl_dat <- sf_fldat %>% 
  rename(date = Date) %>% 
  filter(station %in% 'sac') %>% 
  mutate(
    qsm = stats::filter(q, rep(1, 30)/30, sides = 1, method = 'convolution')
  )
  
# format the data to model
data(sf_dat)
sf_mod <- sf_dat %>% 
  filter(Site_Code %in% 'C3') %>% 
  rename(date = Date) %>% 
  mutate(
    doy = yday(date), 
    dec_time = decimal_date(date), 
    yr = year(date),
    mo = month(date, label = T)
  ) %>% 
  left_join(fl_dat, by = 'date') %>% 
  mutate(
    flo = log(qsm), 
    lnchl = log(chl)
    ) %>% 
  select(-q, -qsm, -station, -Latitude, -Longitude, -Location)

# plot, all
p <- ggplot(sf_mod, aes(x = date, y = lnchl)) + 
  geom_line() +
  theme_bw() 
ggplotly(p)
# boxplot, by years
p <- ggplot(sf_mod, aes(x = yr, y = lnchl)) + 
  geom_boxplot() + 
  theme_bw()
ggplotly(p)
# boxplot, by month
p <- ggplot(sf_mod, aes(x = mo, y = lnchl)) + 
  geom_boxplot() + 
  theme_bw()
ggplotly(p)

Some simple GAMs to explore annual, seasonal trends.

# smooths to evaluate
smths <- c(
  "s(dec_time, bs = 'tp')",  
  "s(doy, bs = 'cc')",
  "te(dec_time, doy, bs = c('tp', 'cc'))"
)

# get all combinations of smoothers to model, one to many
frms <- list()
for(i in seq_along(smths)){
  
 frm <- combn(smths, i) %>%
    apply(2, function(x){
      paste(x, collapse = ' + ') %>% 
        paste('lnchl ~ ', .) %>% 
        formula
    }) 
  
 frms <- c(frms, frm)
 
}

# create models from smooth formula combinations
mods <- map(frms, function(frm){
  
  gam(frm, 
    knots = list(doy = c(1, 366)),
    data = sf_mod, 
    na.action = na.exclude
  )

})
names(mods) <- paste0('mod', seq_along(mods))

Summary stats of annual, seasonal models:

# smoother stats of GAMs
map(mods, ~ summary(.x)$s.table %>% data.frame %>% rownames_to_column('smoother')) %>% 
  enframe %>% 
  unnest %>% 
  kable
name smoother edf Ref.df F p.value
mod1 s(dec_time) 6.866894 7.962040 29.957511 0.0000000
mod2 s(doy) 3.191626 8.000000 12.600387 0.0000000
mod3 te(dec_time,doy) 13.362860 15.974582 27.262699 0.0000000
mod4 s(dec_time) 7.272455 8.281637 35.566876 0.0000000
mod4 s(doy) 3.591968 8.000000 18.279046 0.0000000
mod5 s(dec_time) 7.347362 8.329118 18.745688 0.0000000
mod5 te(dec_time,doy) 8.792719 15.000000 11.089349 0.0000000
mod6 s(doy) 2.933188 8.000000 2.355489 0.0000000
mod6 te(dec_time,doy) 10.642911 12.982207 22.279284 0.0000000
mod7 s(dec_time) 7.332864 8.308760 9.278011 0.0000000
mod7 s(doy) 3.385611 8.000000 5.284500 0.0000000
mod7 te(dec_time,doy) 6.637691 15.000000 1.417708 0.0003557
# summary stats of GAMs
map(mods, ~ data.frame(
    AIC = AIC(.x), 
    R2 = summary(.x)$r.sq)) %>% 
  enframe %>% 
  unnest %>% 
  kable
name AIC R2
mod1 1117.9219 0.3025777
mod2 1215.8161 0.1606211
mod3 995.0956 0.4490483
mod4 986.8771 0.4548302
mod5 972.2099 0.4741757
mod6 992.1514 0.4522078
mod7 971.9230 0.4755770
# prediction data
pred_dat <- data.frame(
    dec_time = seq(min(sf_mod$dec_time), max(sf_mod$dec_time), length = 1000)
  ) %>% 
  mutate(
    date = date_decimal(dec_time), 
    date = as.Date(date),
    mo = month(date, label = TRUE), 
    doy = yday(date), 
    yr = year(date)
  ) %>% 
  left_join(., fl_dat[, c('date', 'qsm')]) %>% 
  mutate(flo = log(qsm)) %>% 
  select(-qsm)

# predictions
sf_res <- map(mods, function(x){
  pred_dat %>% 
    mutate(
      pred = predict(x, newdata = pred_dat)
    )
  }) %>% 
  enframe('mods') %>% 
  unnest

# plot
p <- ggplot(sf_res, aes(x = date)) + 
  geom_point(data = sf_mod, aes(y = lnchl), size = 0.5) + 
  geom_line(aes(y = pred, colour = mods)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    )
ggplotly(p)
# plot
p <- ggplot(sf_res, aes(x = doy, group = factor(yr), colour = yr)) + 
  geom_line(aes(y = pred)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    ) + 
  facet_wrap(~ mods, ncol = 2)
ggplotly(p)

Adding flow data to the model:

# smooths to evaluate
smths <- c(
  "s(dec_time, bs = 'tp')",  
  "s(doy, bs = 'cc')",
  "s(flo, bs = 'tp')",
  "te(flo, doy, bs = c('tp', 'cc'))", 
  "te(flo, dec_time, bs = c('tp', 'tp'))",
  "te(dec_time, doy, bs = c('tp', 'cc'))",
  "te(dec_time, doy, flo, bs = c('tp', 'cc', 'tp'))"
)

# get all combinations of smoothers to model, one to many
frms <- list()
for(i in seq_along(smths)){
  
 frm <- combn(smths, i) %>%
    apply(2, function(x){
      paste(x, collapse = ' + ') %>% 
        paste('lnchl ~ ', .) %>% 
        formula
    }) 
  
 frms <- c(frms, frm)
 
}

# create models from smooth formula combinations
mods2 <- map(frms, function(frm){
  
  gam(frm, 
    knots = list(doy = c(1, 366)),
    data = sf_mod, 
    na.action = na.exclude
  )

})
names(mods2) <- paste0('mod', seq_along(mods2))

Summary stats of best year/season model, year/season/flow model

# best model with only season, year
best1 <- map(mods,  AIC) %>% 
  unlist %>% 
  which.min %>% 
  mods[[.]]

# best model with season, year, flow
best2 <- map(mods2, AIC) %>% 
  unlist %>% 
  which.min %>% 
  mods2[[.]] 

best <- list(best1 = best1, best2 = best2)

# smoother stats of GAMs
map(best, ~ summary(.x)$s.table %>% data.frame %>% rownames_to_column('smoother')) %>% 
  enframe %>% 
  unnest %>% 
  kable
name smoother edf Ref.df F p.value
best1 s(dec_time) 7.332864 8.308760 9.2780106 0.0000000
best1 s(doy) 3.385611 8.000000 5.2844996 0.0000000
best1 te(dec_time,doy) 6.637691 15.000000 1.4177080 0.0003557
best2 s(dec_time) 6.587614 7.657166 8.8044126 0.0000000
best2 s(doy) 3.262079 8.000000 1.1046635 0.0010105
best2 te(flo,dec_time) 10.316629 20.000000 3.8902702 0.0000000
best2 te(dec_time,doy) 8.322306 15.000000 2.1431672 0.0000026
best2 te(dec_time,doy,flo) 8.912490 32.000000 0.9655715 0.0000223
# summary stats of GAMs
map(best, ~ data.frame(
    AIC = AIC(.x), 
    R2 = summary(.x)$r.sq)) %>% 
  enframe %>% 
  unnest %>% 
  kable
name AIC R2
best1 971.9230 0.4755770
best2 869.6463 0.5796506
# predictions
sf_res2 <- map(best, function(x){
  pred_dat %>% 
    mutate(
      pred = predict(x, newdata = pred_dat)
    )
  }) %>% 
  enframe('mods') %>% 
  unnest

# plot
p <- ggplot(sf_res2, aes(x = date)) + 
  geom_point(data = sf_mod, aes(y = lnchl), size = 0.5) + 
  geom_line(aes(y = pred, colour = mods)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    )
ggplotly(p)
ptheme <- theme(
  axis.title.x = element_blank(), 
  axis.title.y = element_blank()
)
cols <- 'Spectral'
pb1 <- dynagam(best1, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') +
  ggtitle('Best 1')
pb2 <- dynagam(best2, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  ggtitle('Best2')
pleg <- g_legend(pb2)
pb2 <- pb2 + 
  theme(legend.position = 'none')

grid.arrange(
  pleg, 
  arrangeGrob(pb1, pb2, ncol = 2, bottom = 'lnQ', left = 'lnchl'), 
  ncol = 1, 
  heights = c(0.1, 1)
)